import os
import sys
import re
import requests
import json
import random
import time

class WeChatArticle(object):
    save_dir = './'
    url = 'https://mp.weixin.qq.com/cgi-bin/appmsg'
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
        'cookie': 'ua_id=GmT2k7KrWTFINxKPAAAAABCXsJSZ9W7S9c0v5JinmPA=; mm_lang=zh_CN; pgv_pvi=1585927168; RK=opoQhfrpE3; ptcz=c9db4af23ff5781e65780d63de1a5dcdd06bf1b0acb5fbb021931a6932b933e5; noticeLoginFlag=1; pgv_pvid=4226171508; ptui_loginuin=2764888380; pgv_si=s5618691072; rewardsn=; wxtokenkey=777; ticket_id=gh_9fcc355cd60c; cert=HkQV50KiTozB3hKSXwwhbL42KWQ1CTGb; pgv_info=ssid=s6551909800; uin=o1342844995; skey=@QG2giDpui; uuid=cb5b1044f2e8af02aa132c026c4c44fc; ticket=eb127d0cb6338b4f2bf0ae1064e58d3dba9047de; rand_info=CAESIFtrNW31mO/409ug3BMyDUQZMHUK3yirJc9H9aQY0SvW; slave_bizuin=3538830699; data_bizuin=3577584030; bizuin=3538830699; data_ticket=iPfCnzAjwj4+n9RhoAKPvMZZ9jKEbqFg0bNNrDhp44uTxnLobFYC4nVDzon5kvOR; slave_sid=SDVFVmw2OUxyZ3BGOFFVSUtJaVlFNnhaT2VJS3FvVlZYRERIcE5Cb2x2M3RyS0NhN005UjRsSU5ZYXlNMEhjT01GTnVSZXhfRG1nTHN3bXhUUTNiMG1uVDVEMzZBSmF4ZmxJa25BdHJUTHJLR09HaVlLZWw1VU9NcnVSMzFieDROeW4wdHRXOE5CY1diT0wy; slave_user=gh_9fcc355cd60c; xid=e9927fc4939965a1113e222f7a9877cf; openid2ticket_onpk91aWV7SWw4aUp62Sy65ap3jc=SIoFOyN9fuqPspUgKW7HEZJuXECfSJw8wNoNFEtTt2U=',
        'referer': 'https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=10&token=317189952&lang=zh_CN'
    }
    def __init__(self, article_name, begin=0):
        self.params = {
            # token在登录后获取， begin默认为0,从头开始， fakeid为需要爬取的公众号id， random为随机数，爬取一次改变一次
            'token': '317189952', 'begin': begin, 'fakeid': 'MjM5Mzg3OTg4MQ==', 'random': '0.9870825068837934',
            'lang': 'zh_CN', 'f': 'json', 'ajax': '1', 'action': 'list_ex', 'count': '5', 'query': '', 'type': '9',
        }
        # 获取文章总数
        self.get_article_sum()
        # 保存的文件夹如果不存在则创建
        self.folder_exist(self.save_dir)
        # 保存文章信息的文件路径
        self.save_filepath = os.path.join(self.save_dir, article_name+'.csv')
        
    def unix_to_date(self, str_unix):
        '''
        1. 作用：把unix时间戳转为年月日字符串
        2. 参数：str_unix:unix时间戳
        3. 返回值：年月日字符串
        '''
        time_array = time.localtime(str_unix)
        str_time = time.strftime("%Y%m%d", time_array)
        return str_time

    # 获取一个随机数
    def get_random(self):
        return '%.15f'%random.random()

    def get_article_sum(self):
        response = requests.get(url=self.url, params=self.params, headers=self.headers)
        response.encoding='utf8'
        content = json.loads(response.text)
        self.end = content['app_msg_cnt']

    # 获取五篇文章
    def get_article_info(self):
        self.params['random'] = self.get_random()
        response = requests.get(url=self.url, params=self.params, headers=self.headers)
        response.encoding='utf8'
        content = json.loads(response.text)
        try:
            list_article_info = content['app_msg_list']
            return list_article_info
        except Exception as e:
            return None

    # 保存5篇文章信息
    def save_article_info(self, list_article_info):
        for article_info in list_article_info:
            article_title = article_info['title']
            article_link = article_info['link']
            article_date = self.unix_to_date(article_info['create_time'])
            save_content = article_date + ',' + article_title + ',' + article_link + '\n'
            self.file_write(self.save_filepath, save_content)

    # 保存所有文章
    def save_all_article_info(self):
        while self.params['begin'] <= self.end:
            self.params['begin'] += 5
            list_article_info = self.get_article_info()
            self.save_article_info(list_article_info)
            time.sleep(30)

    # 设置起始文章
    def set_article_begin(self, begin):
        self.params['begin'] = begin

    # 设置结束文章
    def set_article_end(self, end):
        self.end = end

    def file_write(self, file_path, content, mode='a', encoding='utf8'):
        '''
        1. 作用:创建文件并把content的内容写入到文件file_path中
        2. 参数:
            file_path:文件路径
            content:文件写入的内容
            mode:文件读写的模式,默认为'w'
            encoding:文件编码,默认为'utf8'
        3. 返回值:None
        '''
        f = open(file=file_path, mode=mode, encoding=encoding)
        f.write(content)
        f.close()

    def folder_exist(self, dir_path):
        '''
        1. 作用:判断文件夹路径是否存在,不存在则创建
        2. 参数:dir_path:文件夹路径
        3. 返回值:None
        '''
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

if __name__ == '__main__':
    wechat_article = WeChatArticle('Python学习联盟')
    wechat_article.save_all_article_info()